package com.project.controller;

import com.github.pagehelper.PageInfo;
import com.project.bean.StudentBean;
import com.project.service.IStudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/student")
public class StudentController1 {
    @Autowired
    private IStudentService service;

    @RequestMapping("/cutAll")
    @ResponseBody
    public String cutAll(@RequestParam(value = "pageNO",defaultValue = "1")int pageNO){
//            Integer pageNO
        PageInfo<StudentBean> pageInfo = service.cutAll(pageNO);

        List<StudentBean> list = pageInfo.getList();

        String info = "<table border='1' width='50%'>";
        info += "<thead><tr><th>编号</th><th>姓名</th><th>生日</th><th>成绩</th><th>操作</th></tr></thead>";

        info += "<tbody>";
        for(StudentBean s : list){
            info += "<tr><td>"+s.getId()+"</td><td>"+s.getName()+"</td>"+
                    "<td>"+s.getBirthday()+"</td><td>"+s.getGrade()+"</td>"
                    + "<td><a href='/student/del/"+ s.getId() +"'>删除     </a>" +
                    "<a href='/student/findById?id="+ s.getId() +"'>修改</a></td></tr>";
        }
        info += "</tbody></table>";

        for(int i= 1;i <= pageInfo.getPages();i++){
            info += "<a href='/student/cutAll?pageNO="+i+"' style='margin-left:10px'>"+i+"</a>";
        }

        info += "<div><a href='/html/register.html'>添加</a></div>";

        return info;
    }

    @RequestMapping(value = "/register",method = RequestMethod.GET)//该方法只能以GET方法请求访问
    public String add(StudentBean student){
        service.addStudent(student);
        return "redirect:/student/cutAll";
    }

//    @RequestMapping("/del")
//    public String del(Integer id){
//        service.del(id);
//        return "redirect:/student/cutAll";
//    }

    @RequestMapping("/del/{ss}")//rest风格
    public String del(@PathVariable("ss") int id){
        service.del(id);
        return "redirect:/student/cutAll";
    }

    @RequestMapping("/findById")
    @ResponseBody
    public String findById(int id){
        StudentBean student = service.findById(id);
        String info = "<form action='/student/update'>";
        info += "姓名：" + student.getName() + "<br>";
        info += "生日：" + student.getBirthday() + "<br>";
        info += "成绩：<input type='text' name='grade' value='"+ student.getGrade() +"'>";
        info += "<input type='hidden' name='id' value='"+id+"'>";
        info += "<input type='submit' value='修改'>";
        info += "</form>";
        return info;
    }

    @RequestMapping("/update")
    public String del(int id, int grade){
        service.update(id,grade);
        return "redirect:/student/cutAll";
    }

}
